package com.chenfan.magic.interpreter;

import com.chenfan.magic.core.IdcEngineEntry;
import com.chenfan.magic.core.MagicLogPublisher;
import com.chenfan.magic.entity.TTLDetailModel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import javax.script.ScriptException;
import java.util.Map;

/**
 * @author lm
 * 字符串表达式计算工具
 * <p>
 * 示例: run("86400*3", 0);
 */
@Slf4j
@Component
@AllArgsConstructor
public class NashornInterpreter implements __IInterpreter {

    public static final String TYPE_CODE = "nashorn";
    public static final String ALIAS = "nas";

    @Override
    public Object run(Map<String, Object> idcRuntimePool, String expression, String defaultValue) {
        TTLDetailModel ttlDetailModel = new TTLDetailModel();
        ttlDetailModel.start();
        Object result = null;
        try {
            ScriptEngineManager scriptEngineManager = new ScriptEngineManager();
            ScriptEngine scriptEngine = scriptEngineManager.getEngineByName(TYPE_CODE);
            result = scriptEngine.eval(expression);
            MagicLogPublisher.publishInterpreterEvent(TYPE_CODE, expression, result, null, ttlDetailModel.end().getTtl() + "");
        } catch (ScriptException e) {
            e.printStackTrace();
            IdcEngineEntry.throwException(idcRuntimePool, null, e);
            MagicLogPublisher.publishInterpreterEvent(TYPE_CODE, expression, result, null, ttlDetailModel.end().getTtl() + "", e);
        }
        return result != null ? result : defaultValue;
    }

    @Override
    public Object run(Map<String, Object> idcRuntimePool, String code, Map<String, Object> paramMap) {
        return null;
    }
}
